package com.huishu.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huishu.commons.pojo.Result;
import com.huishu.user.pojo.dto.UserRoleDTO;
import com.huishu.user.pojo.model.UserRoleDO;
import com.huishu.user.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author generator@ljj
* @since 2023-04-21
*/
@RestController
@RequestMapping("/user-role")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @PostMapping("/add")
    public Result add(@RequestBody UserRoleDTO userRoleDTO){
        List<UserRoleDO> collect = userRoleDTO.getRoleIds().stream().map(id -> {
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setUserId(userRoleDTO.getUserId());
            userRoleDO.setRoleId(id);
            return userRoleDO;
        }).collect(Collectors.toList());
        userRoleService.saveBatch(collect);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody UserRoleDTO userRoleDTO){
        LambdaQueryWrapper<UserRoleDO> queryWrapper = Wrappers.lambdaQuery(UserRoleDO.class)
                .eq(UserRoleDO::getUserId,userRoleDTO.getUserId());
        userRoleService.remove(queryWrapper);
        List<UserRoleDO> collect = userRoleDTO.getRoleIds().stream().map(id -> {
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setUserId(userRoleDTO.getUserId());
            userRoleDO.setRoleId(id);
            return userRoleDO;
        }).collect(Collectors.toList());
        userRoleService.saveBatch(collect);
        return Result.success();
    }

}
